package com.example.administrator.balcklist;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.CallLog;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.administrator.balcklist.calllog.CallRecord;
import com.example.administrator.balcklist.qcos.GetObject;
import com.example.administrator.balcklist.qcos.PutObject;
import com.example.administrator.balcklist.qcos.QServiceCfg;
import com.example.administrator.balcklist.util.BlackNumUtil;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener{
    QServiceCfg qServiceCfg;
    public static final String TAG = "ouyang";

    List<CallRecord> callRecords;
    ListView listView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        startService(new Intent(this, ListenCallService.class));
        qServiceCfg = QServiceCfg.instance(this);

        // Dynamic add permissions
        final int permissionCheck = ContextCompat.checkSelfPermission(this,
                Manifest.permission.READ_EXTERNAL_STORAGE)
                + ContextCompat.checkSelfPermission(this,Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (permissionCheck== PackageManager.PERMISSION_GRANTED) {
            Log.d("XIAO", "grant all permissions");
        } else if (permissionCheck <= PackageManager.PERMISSION_DENIED) {
            Log.d("XIAO", "need to grant permissions");
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    1);
        }
        listView = findViewById(R.id.listView);
        callRecords = queryCallLog();
        new Thread(new Runnable() {
            @Override
            public void run() {
                new GetObject(qServiceCfg).start();
            }
        }).start();
        List<String> nums = BlackNumUtil.getNums();
        for (CallRecord callRecord : callRecords) {
            if (nums.contains(callRecord.getMatched_number())) {
                callRecord.setIsBlack("已加入黑名单");
            }
        }
        ArrayAdapter<CallRecord> adapter = new ArrayAdapter<>(
                MainActivity.this,android.R.layout.simple_list_item_1,callRecords);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(this);
    }

    @TargetApi(21)
    private List<CallRecord> queryCallLog() {
        //  权限检查
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_CALL_LOG)
                != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode,
            //      String[] permissions,int[] grantResults)
            // to handle the case where the user grants the permission.
            // See the documentation
            // for ActivityCompat#requestPermissions for more details.
            Log.w(TAG, "permission is request");
            /**
             * 动态申请权限
             * 这里没有在
             * onRequestPermissionsResult(int requestCode,
             * String[] permissions,int[] grantResults)方法里面处理
             *
             */
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.READ_CALL_LOG}, 100);

        }
        ContentResolver resolver = getContentResolver();
        Log.i(TAG, "query call log " + resolver);
        //获取cursor对象
        Cursor cursor = resolver.query(CallLog.Calls.CONTENT_URI, new String[]{
                CallLog.Calls.CACHED_FORMATTED_NUMBER,
                CallLog.Calls.CACHED_MATCHED_NUMBER,
                CallLog.Calls.CACHED_NAME,
                CallLog.Calls.TYPE,
                CallLog.Calls.DATE,
                CallLog.Calls.DURATION,
                CallLog.Calls.GEOCODED_LOCATION,
        }, null, null, "date DESC limit 1000");

        /**
         *  "date DESC limit 2"
         *  按时间排序查询2条记录
         */
         List<CallRecord> callRecords = new ArrayList<>();
        Set<String> nums = new HashSet<>();
        if (cursor != null) {
            Log.i(TAG, "cursor length is " + cursor.getCount());
            try {
                while (cursor.moveToNext()) {
                    String number = getNum(cursor.getString(1));
                    if (nums.contains(number)) {
                        continue;
                    }
                    nums.add(number);
                    CallRecord record = new CallRecord(cursor);
                    callRecords.add(record);
                    Log.i(TAG, record.toString());
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                cursor.close();  //关闭cursor，避免内存泄露
            }
        }
        return callRecords;
    }

    private String getNum(String string) {
        if (null == string || string.length() == 0) {
            return null;
        }
        return string.replace(" ","").replace("+86","");
    }

    // TODO: 2018/3/15 0015 这里监听不到，老王处理下 
    @Override
    public void onItemClick(AdapterView<?> adapterView, final View view, int i, long l) {
        final CallRecord callRecord = callRecords.get(i);

        AlertDialog.Builder builder=new AlertDialog.Builder(this);
        builder.setTitle("添加黑名单");//设置对话框的标题
        builder.setMessage("确定要添加"+callRecord.getMatched_number()+"到黑名单？");//设置对话框的内容
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {  //这个是设置确定按钮

            @Override
            public void onClick(DialogInterface arg0, int arg1) {
//                添加到黑名单
                BlackNumUtil.addBlackNum(callRecord.getMatched_number());
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        new PutObject(qServiceCfg).start();
                    }
                }).start();
                Toast.makeText(MainActivity.this, "添加成功", Toast.LENGTH_SHORT).show();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {  //取消按钮
            @Override
            public void onClick(DialogInterface arg0, int arg1) {

            }
        });
        AlertDialog b=builder.create();
        b.show();  //必须show一下才能看到对话框，跟Toast一样的道理
    }


//    @Override
//    public void onClick(View view) {
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                new GetObject(qServiceCfg).start();
//                new PutObject(qServiceCfg).start();
//            }
//        }).start();
//    }

}
